package org.dding.core.mx;

import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.rmi.registry.LocateRegistry;
import java.util.Hashtable;

import javax.management.InstanceNotFoundException;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.management.remote.JMXConnectorServer;
import javax.management.remote.JMXConnectorServerFactory;
import javax.management.remote.JMXServiceURL;

import org.dding.core.log.ILogger;
import org.dding.core.log.LoggerFactory;

public class MSCMBeanServer {

	private MBeanServer mBeanServer = ManagementFactory
			.getPlatformMBeanServer();
	private ILogger logger = LoggerFactory.getLogger(getClass());

	MSCMBeanServer(String port) {
		try {
			int iport = Integer.parseInt(port);
			String host = InetAddress.getLocalHost().getHostAddress();
			JMXServiceURL url = new JMXServiceURL("rmi", null, iport,
					"/jndi/rmi://" + host + ":" + port + "/connector");

			JMXConnectorServer jmxServer = JMXConnectorServerFactory
					.newJMXConnectorServer(url, null, mBeanServer);
			logger.info(url.toString());
			LocateRegistry.createRegistry(iport);
			jmxServer.start();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public ObjectName registerMBean(String domain,
			Hashtable<String, String> hashtable, Object object) {
		MBeanServer mBeanServer = null;
		ObjectName objectName = null;
		try {
			objectName = new ObjectName(domain, hashtable);
			mBeanServer = ManagementFactory.getPlatformMBeanServer();
			mBeanServer.registerMBean(object, objectName);
		} catch (Exception e) {
			logger.error(e);
		}
		return objectName;
	}

	public void unregisterMBean(ObjectName objectName) {
		try {
			mBeanServer.unregisterMBean(objectName);
		} catch (MBeanRegistrationException e) {
			logger.error(e);
		} catch (InstanceNotFoundException e) {
			logger.error(e);
		}
	}
}
